#include "process_enumerator.h"

#include <Windows.h>
#include <tlhelp32.h>

namespace windows
{

process_enumerator::process_enumerator() noexcept : processes_snapshot(::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL))
{
}

std::optional<process> process_enumerator::first() const noexcept
{
    PROCESSENTRY32W process_entry{sizeof(PROCESSENTRY32W)};

    if (::Process32FirstW(processes_snapshot, &process_entry))
        return process{.id = process_entry.th32ProcessID, .name = process_entry.szExeFile};

    return std::nullopt;
}

std::optional<process> process_enumerator::next() const noexcept
{
    PROCESSENTRY32W process_entry{sizeof(PROCESSENTRY32W)};

    if (::Process32NextW(processes_snapshot, &process_entry))
        return process{.id = process_entry.th32ProcessID, .name = process_entry.szExeFile};

    return std::nullopt;
}

} // namespace windows
